package com.example.jianzhioffer;

/**
 * Created by Quincy on 2018/9/10.
 * 判断是否为循坏链表
 */
public class circleList {

    public class ListNode{
        int val;
        ListNode next = null;
        ListNode(int val){
            this.val = val;
        }
    }

    /**
     * 个人想法，保存头节点，判断下一个节点是否等于头节点
     * **/
    public boolean isCircle(ListNode listNode){
        boolean res = false;
        ListNode currentNode = listNode;
        ListNode headNode = listNode;

        while (currentNode != null){
            ListNode nextNode = currentNode.next;
            //如果下一个节点等于保存的节点，说明循环了
            if (nextNode == headNode){
                res = true;
                break;
            }

            currentNode = nextNode;
        }

        return res;
    }

    /**
     *  快慢，两个相等值，一个快速走，一个慢走，若追上，就是环
     * **/

    public boolean isCircleList(ListNode listNode){
        if (listNode == null || listNode.next == null){
            return false;
        }
        ListNode firstNode = listNode;
        ListNode secondNode = listNode;
        boolean res =false;
        while (listNode != null){
            if (firstNode != null){
                firstNode = firstNode.next;
                secondNode = secondNode.next;
            }
            if (firstNode != null){
                firstNode = firstNode.next;
            }
            if (firstNode == secondNode){
                res = true;
                break;
            }
        }
        return res;
    }

    /**
     * 创建循环链表
     * */
    public void createCircularLinkList(ListNode node){
        ListNode currentNode = node;
        while (currentNode.next != null){
            currentNode = currentNode.next;
        }
        currentNode.next = currentNode;
    }

    /**
     * 打印循环链表
     * */
    public void printCircularLinkList(ListNode node){
        ListNode currentNode = node;
        while (currentNode.next != node){

            System.out.println(currentNode.val + " ");
            currentNode = currentNode.next;
        }
        System.out.println(currentNode.val + " ");

    }
}
